<template>
    <!-- 返回个人资料 -->
    <div class="headerbox">
        <div class="header">
            <van-nav-bar title="个人资料" left-text="返回" left-arrow @click-left="back" />
        </div>
    </div>

    <!-- 个人头像 -->
    <div class="user" style="margin-bottom: 0; margin-top: 1rem;">
        <div class="user-image">
            <img v-if="LoginUser.avatar" :src="LoginUser.avatar" />
            <img v-else src="/assets/images/01.jpg" />
        </div>
    </div>

    <!-- 表单内容 -->
    <div class="form">

        <van-form @submit='profile'>
            <!-- 昵称 -->
            <div class="items">
                <van-field v-model="LoginUser.nickname" name="nickname" label="昵称" placeholder="请输入昵称"
                    :rules="rules.nickname" />
            </div>

            <!-- 邮箱 -->
            <div class="items">
                <van-field v-model="LoginUser.email" name="email" label="邮箱" placeholder="请输入登录邮箱"
                    :rules="rules.email" />
            </div>

            <!-- 密码-->
            <div class="items">
                <van-field v-model="password" name="password" label="密码" type="password" placeholder="请输入登录密码" />
            </div>

            <!-- 性别 -->
            <div class='items'>
                <van-field name="sex" label="性别">
                    <template #input>   
                        <van-radio-group v-model="LoginUser.sex" direction="horizontal">
                            <van-radio name="1">男</van-radio>
                            <van-radio name="2">女</van-radio>
                            <van-radio name="0">保密</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
            </div>

            <!-- 地区 -->
            <div class="items">
                <van-field v-model="LoginUser.region_text" label="地区选择" name="region_text" placeholder="请选择省市区" is-link
                    readonly @click="ShowArea=true" />
            </div>

            <!-- 个人简介 -->
            <div class="items">
                <van-field v-model="LoginUser.content" row='2' name="content" label="个人简介" type="textarea"
                    placeholder="请输入个人简介" maxlength="50" show-word-limit />
            </div>

            <!-- 头像 -->
            <div class="items">
                <van-field name="avatar" label="头像修改">
                    <template #input>
                        <!-- 文件上传组件  v-model默认值-->
                        <van-uploader v-model="avatar" :max-count='1' />
                    </template>
                </van-field>
            </div>

            <!-- 封面 -->
            <div class="items">
                <van-field name="cover" label="背景封面">
                    <template #input>
                        <!-- 文件上传组件  v-model默认值-->
                        <van-uploader v-model="cover" :max-count='5' :before-delete="del" :after-read="add" />
                    </template>
                </van-field>
            </div>


            <!-- 提交按钮 -->
            <div style="width: 50%; margin: 0 auto">
                <van-button round block type="primary" native-type="submit">
                    确认修改
                </van-button>
            </div>
        </van-form>

    </div>
    <!-- 引入地区弹出层 点击地区时，弹出层出现-->
    <van-popup v-model:show="ShowArea" position="bottom">
        <!-- 地区组件 -->
        <van-area :value="region" :area-list="areaList" @confirm="SelectRegion" @cancel="ShowArea = false" />
        <!--value给最后一个地区码就可以了，其余两个就自动  @cancel取消  SelectRegion选择的时候-->
    </van-popup>
</template>

<script>
    // 引入地区初始化数据
    import {
        areaList
    } from '@vant/area-data';

    export default {
        // 设置组件名字
        name: 'BaseProfile',
        // 自动运行钩子函数（在出现之前就改变图片）
        created() {
            var cover = this.$cookies.get('LoginUser').cover
            var list = []

            for (var item of cover) {
                list.push({
                    url: item
                })
            }
            this.cover = list //覆盖下面cover字段
        },
        // 基本数据
        data() {
            return {
                password: "",
                LoginUser: this.$cookies.get('LoginUser'),
                // 地区初始化数据
                areaList,
                ShowArea: false,

                avatar: [{
                    url: this.$cookies.get('LoginUser').avatar
                }],

                cover: [],

                // 创建表单验证
                rules: {

                    nickname: [{
                        required: true,
                        message: '请输入昵称'
                    }],

                    email: [{
                            required: true,
                            message: "请输入登录邮箱"
                        },
                        {
                            message: '邮箱输入格式有误',
                            validator(value) {
                                //正则表达式
                                var reg = new RegExp(
                                    "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"
                                )

                                //test方法返回true 和 false 
                                return reg.test(value)
                            }
                        }
                    ],
                }

            }
        },

        computed: {
            region() {
                // 判断，原来用户选择地址的时候有没有完全选齐，逻辑判断地区
                var province = this.LoginUser.province
                var city = this.LoginUser.city
                var district = this.LoginUser.district

                var region = '' //框架要求是字符串

                //判断是否有选择省份，就把省份赋值给变量
                if (province) {
                    region = province
                }

                if (city) {
                    region = city
                }

                if (district) {
                    region = district
                }

                return region.toString()
            },
            del() {
                return async (detail) => {
                    // 组装数据
                    var data = {
                        action: 'del',
                        userid: this.LoginUser.id,
                        url: detail.url
                    }

                    // 同步
                    var result = await this.$api.cover(data)
                    // 提示信息
                    if (result.code == 0) {
                        this.$notify({
                            message: result.msg,
                            duration: 1000,
                        })
                        return false
                    }

                    // 将cookie覆盖
                    this.$cookies.set('LooginUser', result.data)

                    var cover = result.data.cover
                    var list = []

                    for (var item of cover) {
                        list.push({
                            url: item
                        })
                    }

                    this.cover = list
                    return true
                }
            },

            // 添加图片
            add() {
                return async (file, detail) => {
                    // 组装数据
                    var data = {
                        action: 'add',
                        userid: this.LoginUser.id, //更新了哪个用户
                        cover: file.file
                    }
                    // 同步
                    var result = await this.$api.cover(data)
                    if (result.code == 0) {
                        this.$notify({
                            message: result.msg,
                            duration: 1000,
                        })

                        return false
                    }

                    // 设置覆盖cookies
                    this.$cookies.set('Loginuser', result.data.data)

                    var cover = result.data.data.cover
                    var list = []
                    for (var item of cover) {
                        list.push({
                            url: item
                        })
                    }
                    this.cover = list
                    return true
                }
            }

        },
        methods: {
            // 返回按钮
            back() {
                this.$router.go(-1) //返回上一级
            },
            // 选择地区的方法
            SelectRegion(value) {
                // 点击确认隐藏
                this.ShowArea = false

                // 将修改的元素，赋值到省市区
                let [province, city, district] = value

                var region_text = ''

                if (province) {
                    // 修改cookies
                    this.LoginUser.province = province.code
                    // 拿到名字
                    region_text += `${province.name}/`
                }


                if (city) {
                    // 修改cookies
                    this.LoginUser.city = city.code
                    // 拿到名字
                    region_text += `${city.name}/`
                }


                if (district) {
                    // 修改cookies
                    this.LoginUser.district = district.code
                    // 拿到名字
                    region_text += `${district.name}`
                }

                this.LoginUser.region_text = region_text

            },

            // 提交个人资料
            async profile(form) {
                //组装数据
                var data = {
                    id: this.LoginUser.id,
                    nickname: form.nickname,
                    email: form.email,
                    sex: form.sex,
                    content: form.content,

                    province: this.LoginUser.province,
                    city: this.LoginUser.city,
                    district: this.LoginUser.district,
                }
                // console.log(data);

                // 密码不为空，才修改
                if (form.password) {
                    data.password = form.password //有就塞到数组里面
                }

                // 如果有选择图片就上传
                // 因为头像只上传一张而已，所以只看0 下标，有没有file属性,有说明上传了图片（上传，与未上传时 这个结论是打印对比出来的）
                if (form.avatar[0].file) {
                    data.avatar = form.avatar[0].file //有就塞到数组里面
                }

                // 调用接口
                var result = await this.$api.profile(data)

                if (result.code == 0) {
                    this.$notify({
                        message: result.msg,
                        duration: 1000,
                    })

                } else {
                    this.$notify({
                        type: 'success',
                        message: result.msg,
                        duration: 1000,
                        onClose: () => {
                            // 覆盖cookies
                            this.$cookies.set('LoginUser', result.data)
                            //跳转会会员中心
                            this.$router.go(-1)
                        }
                    })
                }
            },

        },


    }
</script>

<!-- 引入样式 -->
<style>
    @import url('/public/assets/css/profile.css');
</style>